<template>
  <UploadExcel :on-success="handleSuccess"></UploadExcel>
</template>

<script>
import { reqImportEmployee } from '@/api/employees'
export default {
  name: 'Index',

  data() {
    return {
      results: '',
      header: '',
    }
  },

  mounted() {},

  methods: {
    // 成功后触发事件
    handleSuccess({ results, header }) {
      if (this.$route.query.type === 'user') {
        // 批量导入员工
        this.handleAddSuccessBatch(results, header)
      } else if (this.$route.query.type === 'xinshui') {
        // 批量导入社保
      }else{
        // 批量导入薪水
      }
    },

    async handleAddSuccessBatch(results, header) {
      // 一个中文字段映射一个英文
      const userRelations = {
        入职日期: 'timeOfEntry',
        手机号: 'mobile',
        姓名: 'username',
        转正日期: 'correctionTime',
        工号: 'workNumber',
      }

      this.results = results

      this.header = header
      // 展开原数组对象的对象数据
      const arr = []
      results.forEach((item) => {
        const obj = {}

        for (const key in item) {
          // console.log(userRelations[key],'映射键');
          // 取得英文键值

          if (
            userRelations[key] === 'timeOfEntry' ||
            userRelations[key] === 'correctionTime'
          ) {
            userRelations[key] = this.formatExcelDate(item[key])
          }
          obj[userRelations[key]] = item[key]
        }
        arr.push(obj)
      })
      const res = await reqImportEmployee(arr)
      console.log(res)
      this.$message.success('批量导入数据成功')
      this.$router.push('/employees')
    },

    // elxs过滤时间格式
    formatExcelDate(numb, format) {
      const time = new Date((numb - 1) * 24 * 3600000 + 1) // 毫秒
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return (
          year +
          format +
          (month < 10 ? '0' + month : month) +
          format +
          (date < 10 ? '0' + date : date)
        )
      }
      return (
        year +
        (month < 10 ? '0' + month : month) +
        (date < 10 ? '0' + date : date)
      )
    },
  },
}
</script>

<style scoped>
</style>